// src/composables/useProxy.js
import { computed } from 'vue';
import { useRoute } from 'vue-router';

export const useProxy = (options = {}) => {
  const {
    proxyApi,
    gridRef,
    page = true,
    selectOption,
    extraParams = computed(() => ({})), // 用于扩展过滤条件
  } = options;

  const currentRoute = useRoute();

  /**
   * 生成代理配置
   */
  const proxyConfig = computed(() => {
    return {
      sort: true,
      form: true,
      page,
      filter: true,
      response: computed(() => {
        return page ? { result: 'data', total: 'total' } : { list: 'data' };
      }),
      ajax: {
        async query({ page, form, sorts, filters }) {
          console.log('query', page);
          try {
            // 合并所有参数
            const queryParams = {
              ...form,
              ...currentRoute.query,
              ...extraParams.value,
            };

            // 添加排序参数
            if (sorts.length > 0) {
              queryParams.order_by = sorts
                .map((item) => `${item.field}|${item.order}`)
                .join(',');
            }

            // 添加分页参数
            if (page) {
              queryParams.page_size = page.pageSize;
              queryParams.current_page = page.currentPage;
            }

            // 添加过滤参数
            if (filters) {
              // console.log('filters', filters);
              filters.forEach((item) => {
                queryParams[item.field] = item.datas[0];
              });
            }

            // 调用API获取数据
            const { data: result } = await proxyApi(queryParams);
            if (result.options) {
              selectOption.value = result.options;
            }

            // 设置排序规则
            if (result.sort && gridRef?.value) {
              const sortRules = Object.entries(result.sort).map(
                ([field, order]) => ({ field, order: order.toLowerCase() }),
              );
              gridRef.value.setSort(sortRules);
            }

            return result;
          } catch (error) {
            console.error('Data loading failed:', error);
            throw error;
          }
        },
      },
    };
  });

  return { proxyConfig };
};
